ImagePicker拍照、录制视频、相册选择照片、相册选择视频、上传文件

地址:https://pub.dev/packages/image_picker

注意:android无需配置开箱即用,ios还需要配置info.plist

<key>NSPhotoLibraryUsageDescription</key>
<string>应用需要访问相册读取文件</string>
<key>NSCameraUsageDescription</key>
<string>应用需要访问相机拍照</string>
<key>NSMicrophoneUsageDescription</key>
<string>应用需要访问麦克风录制视频</string>

注意:使用相机拍摄的图像和视频会保存到应用程序的本地缓存中,因此应该只是暂时存在。如果您需要永久存储您挑选的图像,您有责任将其移动到更永久的位置

Flutter image_picker实现相机拍照和相册选择

final ImagePicker _picker = ImagePicker();
XFile? _imageFileDir;

拍照

_takePhoto() async {
  XFile? pickedFile = await _picker.pickImage(
    source: ImageSource.camera, maxWidth: 600, maxHeight: 600);
  if (pickedFile != null) {
    setState(() {
      _imageFileDir = pickedFile;
    });
  }
}

相册选择

_openGallery() async {
  XFile? pickedFile = await _picker.pickImage(
    source: ImageSource.gallery, maxWidth: 600, maxHeight: 600);
  if (pickedFile != null) {
    setState(() {
      _imageFileDir = pickedFile;
    });
  }
}

Flutter image_picker录制视频、相册选择视频

final ImagePicker _picker = ImagePicker();
XFile? _videoFileDir;

录制视频

_pickVideo() async {
  XFile? pickedFile = await _picker.pickVideo(source: ImageSource.camera);
  if (pickedFile != null) {
    await _initVideo(File(pickedFile.path));
    setState(() {
      _videoFileDir = pickedFile;
    });
  }
}

相册选择视频

_openGalleryVideo() async {
  XFile? pickedFile = await _picker.pickVideo(source: ImageSource.gallery);
  if (pickedFile != null) {
    await _initVideo(File(pickedFile.path));
    setState(() {
      _videoFileDir = pickedFile;
    });
  }
}

实现图片视频上传

_openGallery() async {
  XFile? pickedFile = await _picker.pickImage(
    source: ImageSource.gallery, maxWidth: 600, maxHeight: 600);
  if (pickedFile != null) {
    setState(() {
      _imageFileDir = pickedFile;
    });
    _uploadFile(pickedFile.path);
  }
}
/*上传文件*/
_uploadFile(String imagePath) async {
  var formData = FormData.fromMap({
    'name': 'wendux',
    'age': 25,
    'file': await MultipartFile.fromFile(imagePath, filename: 'aaa.png'),
  });
  //https://jd.itying.com/imgupload
  //https://jd.itying.com/public/upload/UCO0ZgNYzxkFsjFcGjoVPxkp.png
  var response = await Dio().post('https://jdmall.itying.com/imgupload',
                                  data: formData);
  print(response);
}

完整代码

import 'dart:io';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:dio/dio.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';
class ImagePickerPage extends StatefulWidget {
  const ImagePickerPage({super.key});
  @override
  State<ImagePickerPage> createState() => _ImagePickerPageState();
}
class _ImagePickerPageState extends State<ImagePickerPage> {
  final ImagePicker _picker = ImagePicker();
  XFile? _imageFileDir;
  XFile? _videoFileDir;
  //配置播放视频
  late VideoPlayerController videoPlayerController;
  late ChewieController chewieController;
  _initVideo(filePath) async {
    videoPlayerController = VideoPlayerController.file(filePath);
    await videoPlayerController.initialize();
    chewieController = ChewieController(
      videoPlayerController: videoPlayerController,
      aspectRatio: videoPlayerController.value.aspectRatio,
      autoPlay: true,
      looping: true,
      optionsBuilder: (context, defaultOptions) async {
        //defaultOptions保存了对应的按钮 先打印然后再去自定义
        return await showModalBottomSheet(
          context: context,
          builder: (context) {
            return SizedBox(
              height: 120,
              child: ListView(
                children: [
                  ListTile(
                    title: const Text("播放速度"),
                    onTap: () {
                      defaultOptions[0].onTap!();
                    },
                  ),
                  ListTile(
                    title: const Text("取消"),
                    onTap: () {
                      Navigator.of(context).pop();
                    },
                  )
                ],
              ),
            );
          });
      },
    );
  }
  @override
  void dispose() {
    videoPlayerController.dispose();
    chewieController.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Title'),
      ),
      body: Center(
        child: ListView(
          padding: const EdgeInsets.all(20),
          children: <Widget>[
            ElevatedButton(
              onPressed: _takePhoto,
              child: const Text("拍照"),
            ),
            ElevatedButton(
              onPressed: _openGallery,
              child: const Text("选择图库照片"),
            ),
            ElevatedButton(
              onPressed: _pickVideo,
              child: const Text("录制视频"),
            ),
            ElevatedButton(
              onPressed: _openGalleryVideo,
              child: const Text("选择视频"),
            ),
            _imageFileDir == null
            ? const Text("")
            : Image.file(File(_imageFileDir!.path)),
            _videoFileDir == null
            ? const Text("")
            : AspectRatio(
              aspectRatio:videoPlayerController.value.aspectRatio,
              child: Chewie(controller: chewieController),
            ),
          ],
        ),
      ),
    );
  }
  /*拍照*/
  _takePhoto() async {
    XFile? pickedFile = await _picker.pickImage(
      source: ImageSource.camera, maxWidth: 600, maxHeight: 600);
    if (pickedFile != null) {
      setState(() {
        _imageFileDir = pickedFile;
      });
    }
  }
  /*相册*/
  _openGallery() async {
    XFile? pickedFile = await _picker.pickImage(
      source: ImageSource.gallery, maxWidth: 600, maxHeight: 600);
    if (pickedFile != null) {
      setState(() {
        _imageFileDir = pickedFile;
      });
      _uploadFile(pickedFile.path);
    }
  }
  //录制视频
  _pickVideo() async {
    XFile? pickedFile = await _picker.pickVideo(source: ImageSource.camera);
    if (pickedFile != null) {
      await _initVideo(File(pickedFile.path));
      setState(() {
        _videoFileDir = pickedFile;
      });
    }
  }
  //选择视频
  _openGalleryVideo() async {
    XFile? pickedFile = await _picker.pickVideo(source: ImageSource.gallery);
    if (pickedFile != null) {
      await _initVideo(File(pickedFile.path));
      setState(() {
        _videoFileDir = pickedFile;
      });
    }
  }
  /*上传文件*/
  _uploadFile(String imagePath) async {
    var formData = FormData.fromMap({
      'name': 'wendux',
      'age': 25,
      'file': await MultipartFile.fromFile(imagePath, filename: 'aaa.png'),
    });
    //https://jd.itying.com/imgupload
    //https://jd.itying.com/public/upload/UCO0ZgNYzxkFsjFcGjoVPxkp.png
    var response = await Dio().post('https://jdmall.itying.com/imgupload',
                                    data: formData);
    print(response);
  }
}

results matching ""

    No results matching ""